﻿using System;
using System.Collections.Generic;

namespace Dino
{
    public partial class UnitOfWork : ISession, IObjectContextProvider, IDisposable
    {
        private readonly IDictionary<Type, IObjectContext> _contexts;

        internal IDictionary<Type, Func<IObjectContext>> ContextFactories { get; set; }

        internal UnitOfWork()
        {
            _contexts = new Dictionary<Type, IObjectContext>();
        }

        /// <summary>
        /// Commits the session across all context's changes
        /// </summary>
        public virtual void Commit()
        {
            foreach (var context in _contexts.Values)
            {
                context.Commit();
            }
        }

        /// <summary>
        /// Get's a specific context from the UnitOfWork's registry
        /// </summary>
        public IObjectContext GetContext<T>() where T : IObjectContext
        {
            if (_contexts.ContainsKey(typeof(T)))
            {
                return _contexts[typeof(T)];
            }
            if (!ContextFactories.ContainsKey(typeof(T)))
            {
                throw new ContextNotRegisteredException(typeof(T));
            }
            var context = ContextFactories[typeof(T)]();
            _contexts[typeof(T)] = context;
            return context;
        }

        public void Dispose()
        {
            foreach (var context in _contexts.Values)
            {
                context.Dispose();
            }
            _contexts.Clear();
        }
    }
}